package cn.iocoder.yudao.framework.common.typehandler;

import cn.iocoder.yudao.framework.common.pojo.HourRange;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/**
 * @author FFFF
 */
@MappedTypes(List.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class HourRangeListTypeHandler extends BaseTypeHandler<List<HourRange>> {


    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<HourRange> parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, JSON.toJSONString(parameter));
    }

    @Override
    public List<HourRange> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String sqlList = resultSet.getString(s);
        return getList(sqlList);
    }

    @Override
    public List<HourRange> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String sqlList = resultSet.getString(i);
        return getList(sqlList);
    }

    @Override
    public List<HourRange> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String sqlList = callableStatement.getString(i);
        return getList(sqlList);
    }

    private List<HourRange> getList(String sqlList) {
        List<HourRange> resultList = null;
        if (sqlList != null && !sqlList.isEmpty()) {
            resultList = JSONArray.parseArray(sqlList, HourRange.class);
        }
        return resultList;
    }
}